package com.pomelo.kill.rabbit;

import com.pomelo.kill.common.Constants;
import com.pomelo.kill.exception.KillException;
import com.pomelo.kill.model.Order;
import com.pomelo.kill.model.Stock;
import com.pomelo.kill.rabbit.domain.MessageEvent;
import com.pomelo.kill.service.OrderService;
import com.pomelo.kill.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class Receiver {

    @Resource
    private OrderService orderService;

    @Resource
    private StockService stockService;

    /**
     * 监听订单处理队列，订单提交成功，将订单添加到数据库，更新库存
     *
     * @param event 订单信息实体
     */
    @RabbitHandler
    @RabbitListener(queuesToDeclare = @Queue(Constants.SECONDS_KILL_ORDER_QUEUE))
    public void order(MessageEvent event) throws KillException {
        Order data = (Order) event.getData();
        Order order = orderService.selectByPrimaryKey(data.getId());
        int key;
        if (order == null) {
            key = orderService.insert(data);
        } else {
            key = orderService.updateByPrimaryKeySelective(data);
        }
        if (key > 0) {
            log.info("订单支付成功");
            Stock stock = stockService.selectByGid(data.getGid());
            stock.setKillStock(stock.getKillStock() - 1);
            stock.setStock(stock.getStock() - 1);
            int update = stockService.updateByPrimaryKeySelective(stock);
            if (update > 0) {
                log.info("修改库存成功");
            } else {
                log.error("修改库存失败");
                return;
            }
        } else {
            log.error("订单支付失败");
            return;
        }
    }
}
